﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace SF.Base.Core
{
	public class RefreshModule : System.Web.IHttpModule
	{
		public void Init(HttpApplication app)
		{
			Logger.Detail("// 注册管道事件");
			// 注册管道事件
			app.AcquireRequestState += new EventHandler(this.OnAcquireRequestState);
		}

		// IHttpModule::Dispose
		public void Dispose()
		{
		}

		// 确定是否正在处理 F5 或后退/前进操作
		private void OnAcquireRequestState(object sender, EventArgs e)
		{
			// 访问 HTTP 上下文
			HttpApplication app = (HttpApplication)sender;
			HttpContext ctx = app.Context;

			// 检查 F5 操作

			int thisTicket;

			if (ctx == null || ctx.Session == null) {
				Logger.Detail("RefreshModule ctx is null");
				return;
			}

			//初始化票证字段
			if (ctx.Session["__LASTREFRESHTICKET"] == null)
			{
				ctx.Session["__LASTREFRESHTICKET"] = 0;
				thisTicket = 0;
			}
			else
			{
				// 读取当前请求的票证（从隐藏字段中）
				thisTicket = Convert.ToInt32(ctx.Request["__CURRENTREFRESHTICKET"]);
			}

			// 读取会话中上次处理的票证（从会话中）
			int lastTicket = Convert.ToInt32(ctx.Session["__LASTREFRESHTICKET"]);

			//Logger.Debug(string.Format("lastTicket = {0}, thisTicket = {1}", lastTicket, thisTicket));

			// 比较两个票证
			if (thisTicket > lastTicket ||
				(thisTicket == lastTicket && thisTicket == 0))
			{
				ctx.Session["__LASTREFRESHTICKET"] = thisTicket;
				ctx.Items["IsPageRefresh"] = false;
			}
			else
			{
				ctx.Items["IsPageRefresh"] = true;
			}

			return;
		}
	}
}
